<template>
    <div class="content" id="peszs">
        <template v-if="Object.keys(mainStore.getfrpList).length > 0">
            <n-space vertical size="large">

                <div class="card" :class="v.status ? '' : 'redg'" v-for="(v, i) in mainStore.getfrpList" :key="i">
                    <div class="box">
                        <div class="head" :class="v.status ? '' : 'red'">
                            Frp
                        </div>
                        <div class="title">
                            <div>{{ v.name }}</div>
                            <div class="uuid">UUID:{{ i }}</div>
                        </div>
                    </div>


                    <div class="box">
                        <n-space size="large">
                            <n-button :type="v.status ? 'error' : 'success'" size="tiny" round
                                @click="frpTun(i, !v.status)">
                                <template #icon>
                                    <i class="iconfont" :class="v.status ? 'icon-yitingzhi' : 'icon-running'"></i>
                                </template>
                                {{ v.status ? '停止' : '启动' }}
                            </n-button>
                            <n-button type="info" size="tiny" round @click="showDrawer('log', i)">
                                <template #icon>
                                    <i class="iconfont icon-rizhi"></i>
                                </template>
                                日志
                            </n-button>
                            <n-button type="info" size="tiny" round @click="showDrawer('config', i)">
                                <template #icon>
                                    <i class="iconfont icon-peishushuju"></i>
                                </template>
                                配置
                            </n-button>


                            <n-popconfirm @positive-click="delFrp(i)" negative-text="取消" positive-text="删除">
                                <template #trigger>
                                    <n-button type="error" size="tiny" round :disabled="v.status">
                                        <template #icon>
                                            <i class="iconfont icon-shanchu"></i>
                                        </template>
                                        删除
                                    </n-button>
                                </template>
                                你确定要执行该操作吗？无法复原！
                            </n-popconfirm>

                        </n-space>
                    </div>
                </div>

            </n-space>

        </template>
        <template v-else>
            <n-empty description="您还没有创建网络映射">
                <template #extra>
                    <n-button @click="active = true" size="small" strong secondary type="primary">
                        创建一个
                    </n-button>
                </template>
            </n-empty>
        </template>

    </div>
    <!-- 悬浮按钮 -->
    <div class="suspend" v-if="Object.keys(mainStore.getfrpList).length > 0">
        <n-button strong circle type="success" size="large" @click="active = true">
            <template #icon>
                <i class="iconfont icon-chuangjian"></i>
            </template>
        </n-button>
    </div>

    <!-- 新建弹窗 -->
    <n-drawer v-model:show="active" placement="top" to="#peszs" default-height="45%">
        <n-drawer-content>
            <template #header>
                新建Frp映射
            </template>

            <n-form ref="formRef" :model="dynamicForm">
                <n-form-item label="映射名称" path="name" :rule="{
                    required: true,
                    message: '请输入正确的映射名称',
                    trigger: ['input', 'blur']
                }">
                    <n-input-group>
                        <n-input v-model:value="dynamicForm.name" placeholder="请输入映射名称" clearable>
                            <template #prefix>
                                <i class="iconfont icon-bianji0"></i>
                            </template>
                        </n-input>
                    </n-input-group>
                </n-form-item>

            </n-form>
            <n-button type="primary" size="small" @click="handleValidateButtonClick" :loading="submitloading">
                <template #icon>
                    <i class="iconfont icon-zhengque"></i>
                </template>
                新建
            </n-button>

        </n-drawer-content>
    </n-drawer>


    <!-- 日志和配置 -->
    <n-drawer v-model:show="activeCl" default-width="70%" placement="right" :resizable="false" to="#peszs">
        <n-drawer-content>
            <template #header>
                {{ showType == 'log' ? '日志查看' : 'Frp配置' }}
                <n-radio-group v-model:value="showType" size="small" @update:value="showTypeupdate">
                    <n-radio-button v-for="(item, index) in guiSelectrList" :key="index" :value="item.value"
                        :label="item.name" :disabled="item.disabled" />
                </n-radio-group>
            </template>

            <div v-if="showType == 'log'">
                <logShow ref="logShowRef" :uuid="selectrFrp" />
            </div>
            <div v-else-if="showType == 'config'">
                <!-- 源码展示 -->
                <div style="margin: 0 0 20px;">
                    <n-button type="primary" size="small" @click="saveFile">
                        <template #icon>
                            <i class="iconfont icon-zhengque"></i>
                        </template>
                        保存
                    </n-button>
                </div>
                <VueCodemirror  v-model:modelValue="editText"
                    :style="{ height: windowHeight + 'px' }" />
            </div>

        </n-drawer-content>
    </n-drawer>
</template>
  
  
<script setup>
import { ref, reactive, onActivated } from "vue";
import { useMainStore } from "@renderer/store/index";
import { useRouter } from 'vue-router';
import { useMessage, useDialog } from 'naive-ui';
let { ipcRenderer } = window.electron;
import logShow from '@renderer/components/log-show.vue';

const message = useMessage();
const dialog = useDialog();
const mainStore = useMainStore();

const active = ref(false);

const activeCl = ref(false);
const showType = ref(null);//显示类型  log 日志  config 配置
const editText = ref('');//配置文本


const submitloading = ref(false);//确定保存的加载状态
const dynamicForm = reactive({});
const formRef = ref(null);

const logShowRef = ref(null);//log组件

const selectrFrp = ref(null);//当前操作的frp的uuid

onActivated(()=>{
    mainStore.updateFrpStatus();//更新全部的frp状态
});

const windowHeight = ref(480);
// 监听窗口大小变化
ipcRenderer.on('update-win-size', (e, data) => {
    windowHeight.value = data[1] - 220;
});



// 监听控制台停止运行
ipcRenderer.on('console_close', (e, key) => {
    if (/^frp\-.*$/i.test(key)) {
        // 设置指定frp关闭了
        mainStore.setFrpStatus(key, false);
    }
});

/**
 * 强制关闭Frp
 */
function closeFrp(uuid) {
    ipcRenderer.invoke('closeProcess', uuid);
}


/**
 * 启动（停止）frp
 * @param {string} uuid 
 */
function frpTun(uuid, status = true) {
    if (!status) {
        // 关闭指定frp
        closeFrp(uuid);
        return;
    }
    window.api.runFrp(uuid).then(res => {
        // 设置指定frp运行效果
        mainStore.setFrpStatus(uuid, res);
    });
}

/**
 * 删除指定uuid的frp
 * @param {string} uuid 
 */
function delFrp(uuid) {
    mainStore.delFrp(uuid);
    message.success('删除成功！');
}

/**
 * 点击确定
 */
function handleValidateButtonClick() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            let newFrpuuid = window.api.newFrp();
            if (newFrpuuid == false) {
                message.error('新建失败！');
                return;
            }
            mainStore.addFrp(dynamicForm.name, newFrpuuid);
            message.success('创建成功！');
            active.value = false;//隐藏弹窗
            dynamicForm.name = '';//清空
        } else {
            message.error(errors[0][0].message);
        }
    })
}

/**
 * 显示弹窗（配置和日志）
 * @param {*} type 
 * @param {*} uuid 
 */
function showDrawer(type, uuid) {
    showType.value = type;
    // 获取指定uuid的type数据
    selectrFrp.value = uuid;//设置当前操作的 （frp）uuid
    if (type == 'config') {
        // 获取配置
        editText.value = window.api.getFrpConfig(uuid);//获取配置信息
    }
    activeCl.value = true;//显示
}
/**
 * 写入配置到文件
 */
function saveFile() {
    window.api.setFrpConfig(selectrFrp.value, editText.value);
    message.success('保存成功！');
}



</script>
  
  
<style lang="scss" scoped>
.content {
    padding: 10px;

    .n-empty {
        margin-top: 30vh;
    }

    .card {
        padding: 10px;
        background-color: rgba(58, 224, 127, 0.3);
        border-radius: 5px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        box-shadow: 5px 8px 10px -7px rgb(58, 224, 127, 0.5);

        .box {
            display: flex;
            align-items: center;

            .head {
                padding: 0 10px;
                height: 20px;
                display: flex;
                justify-self: center;
                align-items: center;
                background-color: #32c971;
                color: #fff;
                border-radius: 15px;
                margin-right: 20px;
            }

            .title{
                .uuid{
                    font-size: 10px;
                }
            }

            .red {
                background-color: rgb(223, 40, 40) !important;
            }
        }



    }

    .redg {
        background-color: rgba(240, 142, 142, 0.3) !important;
        box-shadow: 5px 8px 10px -7px rgba(226, 79, 79, 0.5);
    }

    .whiteg {
        background-color: rgb(255, 255, 255) !important;
    }
}


.suspend {
    position: absolute;
    bottom: 10vh;
    right: 5vw;
    z-index: 99;

    .n-button {
        box-shadow: 5px 5px 12px rgba(24, 160, 88, 0.6);
    }
}
</style>